/*
	Adobe Systems Incorporated(r) Source Code License Agreement
	Copyright(c) 2007 Adobe Systems Incorporated. All rights reserved.
	
	Please read this Source Code License Agreement carefully before using
	the source code.
	
	Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, 
	no-charge, royalty-free, irrevocable copyright license, to reproduce,
	prepare derivative works of, publicly display, publicly perform, and
	distribute this source code and such derivative works in source or 
	object code form without any attribution requirements.  
	
	The name "Adobe Systems Incorporated" must not be used to endorse or promote products
	derived from the source code without prior written permission.
	
	You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and
	against any loss, damage, claims or lawsuits, including attorney's 
	fees that arise or result from your use or distribution of the source 
	code.
	
	THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT 
	ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  ALSO, THERE IS NO WARRANTY OF 
	NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT.  IN NO EVENT SHALL ADOBE
	OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
	OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF
	ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package mx.containers
{
	import mx.containers.Canvas;
	import flash.events.MouseEvent;
	import mx.core.Application;
	import mx.controls.Button;
	import flash.display.DisplayObject;
	import mx.core.EdgeMetrics;
	import mx.containers.Panel;
	import flash.geom.Rectangle;
	import mx.events.CloseEvent;
	import flash.display.NativeWindow;
	import flash.display.NativeWindowResize;
	import flash.filters.DropShadowFilter;
	import flash.display.NativeWindowDisplayState;

	[IconFile("ApplicationWindow.png")]
	public class ApplicationWindow extends Panel 
	{
		
		/********** Button Assets ***************/
		[Embed(source="/assets/window/minimize_icon.png")]
		private var minimizeIcon:Class;
		
		[Embed(source="/assets/window/maximize_icon.png")]
		private var maximizeIcon:Class;
		
		[Embed(source="/assets/window/restore_icon.png")]
		private var restoreIcon:Class;
		
		[Embed(source="/assets/window/close_icon.png")]
		private var closeIcon:Class;

		[Embed(source="/assets/window/minimize_icon_down.png")]
		private var minimizeIconDown:Class;
		
		[Embed(source="/assets/window/maximize_icon_down.png")]
		private var maximizeIconDown:Class;
		
		[Embed(source="/assets/window/restore_icon_down.png")]
		private var restoreIconDown:Class;
		
		[Embed(source="/assets/window/close_icon_down.png")]
		private var closeIconDown:Class;		
		
		[Embed(source="/assets/window/resizeGripper.png")]
		private var gripperClass:Class;		

		import mx.core.mx_internal;
		
		/**
		 *  @private
		 *  Version string for this class.
		 */
		mx_internal static const VERSION:String = "0.1.0.0";
		
		private var minButton:Button;
		private var maxButton:Button;
		private var closeButton:Button;
		private var gripper:DisplayObject;
		
		private var _showMinButton:Boolean = true;
		private var _showMaxButton:Boolean = true;
		private var ___showCloseButton:Boolean = true;
		
		private var _buttonPadding:int = 3;
		
		private const BOTTOM_DRAG_AREA_HEIGHT:int = 12;
		private const SIDE_DRAG_AREA_WIDTH:int = 12;
		private const RESIZE_AREA_DIMENSION:int = 12;
		private const HIT_AREA_PADDING:int = 5;
		
		public function ApplicationWindow()
		{
			super();
			doubleClickEnabled = true;
			addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			addEventListener(MouseEvent.DOUBLE_CLICK, onMouseDown);
		}		
		
		protected override function createChildren():void
		{	 
			super.createChildren();
			
			minButton = new Button();
			minButton.width = 12;
			minButton.height = 12;
			minButton.setStyle("upSkin", minimizeIcon);
			minButton.setStyle("overSkin", minimizeIconDown);
			minButton.setStyle("downSkin", minimizeIconDown);
			minButton.addEventListener(MouseEvent.CLICK, onMinClick);
			
			
			maxButton = new Button();
			maxButton.width = 12;
			maxButton.height = 12;
			maxButton.setStyle("upSkin", maximizeIcon);
			maxButton.setStyle("overSkin", maximizeIconDown);
			maxButton.setStyle("downSkin", maximizeIconDown);
			maxButton.addEventListener(MouseEvent.CLICK, onMaxClick);
			
			closeButton = new Button();
			closeButton.width = 12;
			closeButton.height = 12;
			closeButton.setStyle("upSkin", closeIcon);
			closeButton.setStyle("overSkin", closeIconDown);
			closeButton.setStyle("downSkin", closeIconDown);
			closeButton.addEventListener(MouseEvent.CLICK, onCloseClick);
			

			titleBar.addChild(minButton);
			titleBar.addChild(maxButton);
			titleBar.addChild(closeButton);
			
			gripper = new gripperClass();
			rawChildren.addChild(gripper);
			
			titleTextField.filters = [
				new DropShadowFilter(2, 45, 0x000000)];
		}
		
	 	public override function set enabled(value:Boolean):void
	 	{
	 		super.enabled = value;
	 		
	 		if(closeButton != null)
	 		{
	 			closeButton.enabled = value;
	 		}
	 		
	 		if(minButton != null)
	 		{
	 			minButton.enabled = value;
	 		}
	 		
	 		if(maxButton != null)
	 		{
	 			maxButton.enabled = value;
	 		}
	 	}
		
		protected override function layoutChrome(unscaledWidth:Number,
												 unscaledHeight:Number):void
		{
			//trace("layoutChrome");
			//trace("width : " + unscaledWidth);
			super.layoutChrome(unscaledWidth, unscaledHeight);
			
			var bm:EdgeMetrics = borderMetrics;
			var headerHeight:Number = getHeaderHeight();
			
			var minXPos:Number;
			
			if(_showMinButton)
			{
				minXPos = 0;
				
				if(___showCloseButton)
				{
					minXPos += closeButton.width + _buttonPadding;
				}
				
				if(_showMaxButton)
				{
					minXPos += maxButton.width + _buttonPadding;
				}
				
				
				minButton.setActualSize(
					minButton.getExplicitOrMeasuredWidth(),
					minButton.getExplicitOrMeasuredHeight());

				minButton.move(
					//unscaledWidth - x - bm.right - (10 + minXPos) -
					unscaledWidth - bm.right - (10 + minXPos) -
					minButton.getExplicitOrMeasuredWidth(),
					(headerHeight -
					minButton.getExplicitOrMeasuredHeight()) / 2);	
			}
			
			if(_showMaxButton)
			{		
				minXPos = 0;
				
				if(___showCloseButton)
				{
					minXPos += closeButton.width + _buttonPadding;
				}			
				
				maxButton.setActualSize(
					maxButton.getExplicitOrMeasuredWidth(),
					maxButton.getExplicitOrMeasuredHeight());

				maxButton.move(
					//unscaledWidth - x - bm.right - (10 + minXPos) -
					unscaledWidth - bm.right - (10 + minXPos) -
					maxButton.getExplicitOrMeasuredWidth(),
					(headerHeight -
					maxButton.getExplicitOrMeasuredHeight()) / 2);	
			}
			
			if(___showCloseButton)
			{				
				closeButton.setActualSize(
					closeButton.getExplicitOrMeasuredWidth(),
					closeButton.getExplicitOrMeasuredHeight());

				closeButton.move(
					//unscaledWidth - x - bm.right - 10 -
					unscaledWidth - bm.right - 10 -
					closeButton.getExplicitOrMeasuredWidth(),
					(headerHeight -
					closeButton.getExplicitOrMeasuredHeight()) / 2);	
			}
			
			const ICON_GAP:Number = 4;
			//var titleWidth:Number = mx_internal::titleIconObject.width + ICON_GAP + titleTextField.textWidth;
			var titleWidth:Number = ICON_GAP + titleTextField.textWidth;
			var tempX:Number = (unscaledWidth - titleWidth) / 2;
			
			//mx_internal::titleIconObject.x = tempX;
			//tempX += mx_internal::titleIconObject.width + ICON_GAP;
			tempX += ICON_GAP;
			
			titleTextField.x = tempX;	
			
			gripper.x = unscaledWidth - gripper.width - 2;
			gripper.y = unscaledHeight - gripper.height - 2;
		}
		
		[Inspectable(category="General")]
		public function get showCloseButton():Boolean
		{
			return ___showCloseButton;
		}
	
		public function set showCloseButton(value:Boolean):void
		{
			___showCloseButton = value;
			closeButton.visible = value;
		}
	
		[Inspectable(category="General")]
		public function get showMaximizeButton():Boolean
		{
			return _showMaxButton;
		}
	
		public function set showMaximizeButton(value:Boolean):void
		{
			_showMaxButton = value;
			maxButton.visible = value;
		}	
	
		[Inspectable(category="General")]
		public function get showMinimizeButton():Boolean
		{
			return _showMinButton;
		}
	
		public function set showMinimizeButton(value:Boolean):void
		{
			_showMinButton = value;
			minButton.visible = value;
		}		
		
		protected override function getHeaderHeight():Number
		{
			var headerHeight:Number = getStyle("headerHeight");
			
			if (isNaN(headerHeight))
				headerHeight = measureHeaderText().height + 14;
			
			return headerHeight;
		}
		
		private function measureHeaderText():Rectangle
		{
			var textWidth:Number = 20;
			var textHeight:Number = 14;
			
			if (titleTextField && titleTextField.text)
			{
				textWidth = titleTextField.textWidth;
				textHeight = titleTextField.textHeight;
			}
			
			if (statusTextField)
			{
				textWidth = Math.max(textWidth, statusTextField.textWidth);
				textHeight = Math.max(textHeight, statusTextField.textHeight);
			}
			
			return new Rectangle(0, 0, textWidth, textHeight);
		}		
		
		private function onMouseDown(event:MouseEvent):void
		{
			var doubleClick:Boolean = (event.type == MouseEvent.DOUBLE_CLICK);		
			
			var tmpX:Number = mouseX;
			var tmpY:Number = mouseY;
			
			//top move area
			if((tmpX < minButton.x) && (tmpY < getHeaderHeight()))
			{
				//trace("hit move");
				if(!doubleClick)
				{
					Application.application.systemManager.stage.nativeWindow.startMove();
				}
				else
				{
					if(stage.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED)
					{
						Application.application.systemManager.stage.nativeWindow.restore();
					}
					else
					{
						Application.application.systemManager.stage.nativeWindow.maximize();
					}
					}
				return;
			}
			
			//bottom right resize area
			if((tmpX > width - RESIZE_AREA_DIMENSION) && (tmpY > height - RESIZE_AREA_DIMENSION))
			{
				//trace("hit resize bottom right");
				Application.application.systemManager.stage.nativeWindow.startResize(NativeWindowResize.BOTTOM_RIGHT);
				return;
			}
			
			//bottom left resize area
			if((tmpX < RESIZE_AREA_DIMENSION) && (tmpY > height - RESIZE_AREA_DIMENSION))
			{
				//trace("hit resize bottom left");
				Application.application.systemManager.stage.nativeWindow.startResize(NativeWindowResize.BOTTOM_LEFT);
				return;
			}			
			
			//bottom resize area
			if(tmpY > (height - BOTTOM_DRAG_AREA_HEIGHT) &&
				tmpX > (RESIZE_AREA_DIMENSION + HIT_AREA_PADDING) &&
				tmpX < (width - RESIZE_AREA_DIMENSION - HIT_AREA_PADDING))
			{
				//trace("hit resize bottom");
				Application.application.systemManager.stage.nativeWindow.startResize(NativeWindowResize.BOTTOM);
				return;
			}
			
			//left resize area
			if(tmpX < SIDE_DRAG_AREA_WIDTH &&
				tmpY > (getHeaderHeight() + HIT_AREA_PADDING) &&
				tmpY < height - (RESIZE_AREA_DIMENSION + HIT_AREA_PADDING))		
			{
				//trace("hit resize left");
				Application.application.systemManager.stage.nativeWindow.startResize(NativeWindowResize.LEFT);
				return;
			}	
			
			//right resize area
			if(tmpX > width - SIDE_DRAG_AREA_WIDTH &&
				tmpY > (getHeaderHeight() + HIT_AREA_PADDING) &&
				tmpY < height - (RESIZE_AREA_DIMENSION + HIT_AREA_PADDING))		
			{
				//trace("right resize right");
				Application.application.systemManager.stage.nativeWindow.startResize(NativeWindowResize.RIGHT);
				return;
			}			
		}
		
		private function onCloseClick(event:MouseEvent):void
		{
			//need to broadcast event
			Application.application.systemManager.stage.nativeWindow.close();
		}		
		
		private function onMinClick(event:MouseEvent):void
		{

			Application.application.systemManager.stage.nativeWindow.minimize();
			
		}
		
		private function onMaxClick(event:MouseEvent):void
		{

			if(maxButton.getStyle("upSkin") == maximizeIcon)
			{
				Application.application.stage.nativeWindow.maximize();

				maxButton.setStyle("upSkin", restoreIcon);
				maxButton.setStyle("overSkin", restoreIconDown);
				maxButton.setStyle("downSkin", restoreIconDown);
			}
			else
			{
				Application.application.systemManager.stage.nativeWindow.restore();
				maxButton.setStyle("upSkin", maximizeIcon);
				maxButton.setStyle("overSkin", maximizeIconDown);
				maxButton.setStyle("downSkin", maximizeIconDown);
			}
		
		}
	}
}
